#!/bin/sh
#
# Generates fuzzed samples with ramsada
# run them through DumpRenderTree
#
# This script is started by the run.conf upstart job
# Precondition:
#		exe, test exe, samples installed with bootstrap.sh
#		/etc/taskenv.sh contains all the environment variables needed
# Postcondition:
#		When invoked with 'loop forever' arg
#		runs forever and send a notification 
#		when the exe under test exits with a non 0 status
#
#source the environment variables
. /etc/taskenv.sh
export DISPLAY
Usage() {
echo "Missing argument(s)
Usage:
run.sh loop (forever|<# of iterations>) [log] [crash <frequency>]
example: 
run.sh loop forever		: Runs forever
run.sh loop 50 log	: Runs 50 times and generate pixel log
run.sh loop 50 crash 10	: Runs 50 times and crashes every 10 iteration"
exit 1
}
echo "Starting: $0 with args:$@ ..." 
#
#Parse params
#
#Setup default values
n=0 ; logpixel=0 ; crash=0 ; modcrash=0
#Parse cmd line args
[ $# -ne 0 ] || Usage
while [ $# -gt 0 ]
do
	if [ $1 = loop ] ; then n=$2 ; shift ; shift ; continue ; fi
	if [ $1 = log ] ; then logpixel=1 ; shift ; continue ; fi
	if [ $1 = crash ] ; then crash=1 ; modcrash=$2 ; shift ; shift ; continue ; fi
	echo "Unexpected arg:$1" ; shift
done
#Assert args
[ $n = forever ] || [ $n -gt 0 ] || Usage
[ $crash -eq 0 ] || [ $modcrash -gt 0 ] || Usage
echo "Parsed arguments: n=$n logpixel=$logpixel crash=$crash modcrash=$modcrash"

#
#Generate output files
#
touch /tmp/seed ; touch results
#
#Enter Loop
#
echo "Start Testing $EXE with inputs generated by $RADAMSA"
i=0
while :
do
#generate seed
	SEED=`openssl rand -base64 15`
	echo $SEED > /tmp/seed
#Generate the fuzzed inputs		
   $RADAMSA -n $FUZZCOUNT -s $SEED -o $FUZZDIR/$FUZZOUT $SAMPLEDIR/$FUZZIN
#
#Run DumpRenderTree over all files generated by Radamsa
#Could be only 1 html input refering to several embedded objects
#or many html input files
#
	for file in $FUZZDIR/*.html 
	do
	DRTHTML=$file
#Increase loop count
		i=$(( $i + 1 )) ; #echo "i=$i"
#log iteration number
		echo $i > /tmp/iterN.t ; 
		mv /tmp/iterN.t /tmp/iterN #mv is atomic, echo isn't
#Check if we're asked to crash
		if [ $crash -eq 1 ] && [ `expr $i % $modcrash` -eq 0 ] ; then  DRTHTML=$CRASH ; SEED='InduceCrash' ; fi
#Generate pixel loggin params if needed
		test $logpixel -eq 1 && PIXLOG="--test-shell --pixel-tests=/tmp/pixlog.$i.png"
#
#Run the command
#
		$EXE $PIXLOG  $DRTHTML > /tmp/trace 2>&1 
#
#If exit with error condition, log & notify it
#
		if [ $? -ne 0 ] # test exit value of DumpRenderTree
			then
			echo "Abort Exit with SEED=$SEED" | tee -a results
			date  | tee -a results
			cat /tmp/trace >> results
			#Call SNS Publish with the results
			SUBJECT="DumpRenderTree crash with seed=$SEED"
			MESSAGE=`tail --line=20 /tmp/trace`
			notify.sh "$SUBJECT" "$MESSAGE"
		fi
#Check if we looped up to n		
		if [ $n != 'forever' ] && [ $i -eq $n ] ; then echo "$0 done" ; exit 0 ; fi

	done #for file in $FUZZDIR/*.html 
done

